package com.hanxiaozhang.api.config;

import com.hanxiaozhang.exception.NoFeignDefinitionException;
import com.hanxiaozhang.util.JsonUtil;
import com.hanxiaozhang.util.StringUtil;
import feign.Response;
import feign.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈FeignClient异常解码器〉
 *
 * @author hanxinghua
 * @create 2020/7/16
 * @since 1.0.0
 */
@Slf4j
@Configuration
public class FeignClientErrorDecoder implements feign.codec.ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        String className = null;
        String message = null;
        try {
            if (response.status() == HttpStatus.OK.value()) {
                String errorContent = Util.toString(response.body().asReader());
                Map<String, String> map = JsonUtil.jsonToMapSS(errorContent);
                if (map == null || map.isEmpty() ||
                        StringUtil.isBlank(className = map.get("exception"))) {
                    return new NoFeignDefinitionException();
                }
                message = map.get("message");
                return (Exception) Class.forName(className)
                        .getConstructor(String.class).newInstance(message);
            }
            return new NoFeignDefinitionException("请求错误, Http状态码是：" + response.status());

        } catch (Exception e) {
            log.error("FeignClientErrorDecoder-decode异常,异常信息:[{}]", e);
            return new NoFeignDefinitionException(message == null ? e.getMessage() : message);
        }
    }

}